package com.socialuni.sdk.service.comment;

import com.socialuni.sdk.api.model.RO.comment.TalkCommentRO;
import com.socialuni.sdk.constant.status.ContentStatus;
import com.socialuni.sdk.domain.CommentDomain;
import com.socialuni.sdk.domain.NotifyDomain;
import com.socialuni.sdk.domain.ReportDomain;
import com.socialuni.sdk.factory.TalkCommentROFactory;
import com.socialuni.sdk.model.DO.comment.CommentDO;
import com.socialuni.sdk.model.DO.notify.NotifyDO;
import com.socialuni.sdk.model.DO.user.UserDO;
import com.socialuni.sdk.model.QO.comment.CommentAddVO;
import com.socialuni.sdk.repository.CommentRepository;
import com.socialuni.sdk.repository.NotifyRepository;
import com.socialuni.sdk.repository.TalkRepository;
import com.socialuni.sdk.service.NotifyService;
import com.socialuni.sdk.service.ReportService;
import com.socialuni.sdk.service.ViolationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import java.util.List;

/**
 * @author qinkaiyuan
 * @date 2020-05-16 20:11
 */
@Service
@Slf4j
public class SocialPostCommentService {

    @Resource
    private EntityManager entityManager;

    @Resource
    private CommentRepository commentRepository;

    @Resource
    private TalkRepository talkRepository;

    @Resource
    private NotifyService notifyService;
    @Resource
    private NotifyRepository notifyRepository;
    @Resource
    private ViolationService violationService;
    @Resource
    private ReportService reportService;
    @Resource
    private CommentCheckService commentCheckService;
    @Resource
    private CommentDomain commentDomain;
    @Resource
    private ReportDomain reportDomain;
    @Resource
    private NotifyDomain notifyDomain;


    public TalkCommentRO addComment(CommentAddVO addVO, UserDO requestUser, String threeUnionId) {
        //校验comment
        CommentAddLineTransfer commentAddLineTransfer = commentCheckService.checkCommentAddVO(
                addVO,
                requestUser
        );

        //校验结果
        //校验时候，访问了数据库，存储了talk、parent、reply这些值，方便以后使用，传输使用
        //保存comment，内部关联保存了talk、parentComment、replyComment
        commentAddLineTransfer = commentDomain.saveComment(addVO, commentAddLineTransfer, requestUser.getId(), threeUnionId);

        CommentDO commentDO = commentAddLineTransfer.getCommentDO();

        // 校验是否触发关键词
        reportDomain.checkKeywordsCreateReport(commentDO);

        //如果不为待审核，才发送通知
        if (commentDO.getStatus().equals(ContentStatus.enable)) {
            List<NotifyDO> notifyDOS = notifyDomain.saveCreateCommentNotifies(commentDO, commentAddLineTransfer.getTalk(), commentAddLineTransfer.getParentComment(), commentAddLineTransfer.getReplyComment(), requestUser);

            //推送消息
            notifyService.sendNotifies(notifyDOS, requestUser);
        }
        

        return TalkCommentROFactory.newTalkCommentVO(requestUser, commentDO, false);
    }
}
